$(function () {

    // 初始化话题内容富文本框
    initSNU({
        id: 'content',
        gs: true,
        height: 360,
        toolsArr: [['insert', ['myImage', 'link']]],
        type: 1,
        video: true
    });

    $('body')
        .on('ifChanged', 'input[name=reply]', function () {
            $('input[name=replyPermission]').parents('div.form-group').toggleClass('hide', !isPermitReply());
        })
        .on('click', '#selectClasses', function () {
            selectClasses();
        })
        .on('click', 'i.fa-trash', function () {
            $(this).parents('tr').remove();
            var isEmpty = $('#classes-task-classes tr[data-classes]').length == 0;
            $('#classes-task-classes div.noDataTipsBox').parents('tr').toggleClass('hide', !isEmpty);
        })
        .on('click', '#savePublish', function () {
            saveClassesTopic();
        })
        .on('click', '#saveCancel', function () {
            window.location = baseloaction + '/admin/classes/topic/topicList';
        });

    /**
     * 是否允许回复
     * @return {boolean}
     */
    function isPermitReply() {
        return $('input[name=reply]:checked').val() == 1;
    }

    /**
     * 查找添加样式
     */
    function selectClasses() {
        parent.layer.open({
            type: 2,
            shadeClose: false,
            shade: [0.3, '#000000'],
            title: '<strong>选择班级</strong>',
            area: winArea,
            content: baseloaction + "/admin/classes/selectClassesList?type=1",
            btn: ['选择', '取消'],
            yes: function (index) {
                var frame = parent.layer.getChildFrame('body', index);
                var checked = frame.find('input[name=id]:checked');
                if (checked.length == 0) {
                    icModale(0, '选择班级');
                } else {
                    var classes = checked.map(function (v) {
                        var tr = $(this).parents('tr');
                        var clazz = {};
                        clazz.id = tr.data('id');
                        clazz.name = tr.data('name');
                        return clazz;
                    }).toArray();
                    selectClassesCallback(classes);
                    parent.layer.close(index);
                }
            }
        });

        /**
         * 选择课程回调
         * @param classes 回调班级数据
         */
        function selectClassesCallback(classes) {
            $('#classes-topic-classes div.noDataTipsBox').parents('tr').toggleClass('hide', classes.length > 0);
            classes.forEach(function (v) {
                var id = v.id;
                if ($('#classes-topic-classes tr[data-classes=' + id + ']').length == 0) {
                    $('#classes-topic-classes').append('<tr data-classes="' + v.id + '">' +
                        '<td class="text-center">' + v.id + '</td>' +
                        '<td class="text-center">' + v.name + '</td>' +
                        '<td class="text-center"><a href="javascript:void(0)" data-original-title="删除" data-toggle="tooltip" class="c-master fs14"><i class="fa fa-trash"></i></a></td>' +
                        '</tr>');
                }
            });
            $('#classes-task-classes a[data-toggle=tooltip]').tooltip();
        }
    }

    function preHandleTopicImages() {
        var content = $('#content').summernote('code');
        var images = $($.parseHTML(content)).find('img');
        if (images.length > 0) {
            return images.map(function () {
                return this.src;
            }).get().join(',');
        }
        return '';
    }

    /**
     * 保存班级话题
     */
    function saveClassesTopic() {
        var params = $('#classes-topic-form').serializeJSON();
        params.id = $('#id').val();
        params.content = $('#content').summernote('code');
        params.classesIds = getClasses();
        params.classify = $('#topic-type-select').val();
        //params.topicImages = preHandleTopicImages();
        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + '/admin/classes/topic/saveTopic',
            data: params,
            dataType: 'json',
            type: 'post',
            contentType: 'application/json;charset=utf-8',
            success: function (response) {
                icModale(0, response.message);
                if (response.success) {
                    var crumbs = $("#crumbs").val();
                    if (crumbs) {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    } else {
                        window.location = baseloaction + '/admin/classes/topic/topicList';
                    }
                }
            }
        });
    }

    function getClasses() {
        var classes = $('#classes-topic-classes tr[data-classes]');
        if (classes.length > 0) {
            return classes.map(function () {
                return this.dataset['classes'];
            }).get().join(',');
        }
        return '';
    }
});